#!/bin/bash

# QEMU K8s网络配置脚本
# 创建网桥并配置网络环境

set -e

# 加载配置文件
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SOURCE_DIR/config.conf"

# 检查是否以root权限运行
if [ "$EUID" -ne 0 ]; then
    echo "错误: 此脚本需要root权限运行"
    echo "请使用: sudo $0"
    exit 1
fi

echo "开始配置QEMU K8s网络环境..."

# 安装必要的网络工具
echo "检查并安装必要的网络工具..."
if command -v yum >/dev/null 2>&1; then
    yum install -y bridge-utils net-tools
elif command -v apt-get >/dev/null 2>&1; then
    apt-get update
    apt-get install -y bridge-utils net-tools
else
    echo "警告: 无法自动安装bridge-utils，请手动安装"
fi

# 检查网桥是否已存在
if ip link show "$BRIDGE_NAME" >/dev/null 2>&1; then
    echo "网桥 $BRIDGE_NAME 已存在"
    read -p "是否重新配置? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo "删除现有网桥..."
        ip link set "$BRIDGE_NAME" down 2>/dev/null || true
        brctl delbr "$BRIDGE_NAME" 2>/dev/null || true
    else
        echo "保持现有网桥配置"
        exit 0
    fi
fi

# 创建网桥
echo "创建网桥: $BRIDGE_NAME"
brctl addbr "$BRIDGE_NAME"

# 配置网桥IP
echo "配置网桥IP: $GATEWAY_IP"
ip addr add "$GATEWAY_IP/24" dev "$BRIDGE_NAME"
ip link set "$BRIDGE_NAME" up

# 启用IP转发
echo "启用IP转发..."
echo 1 > /proc/sys/net/ipv4/ip_forward

# 配置iptables规则以支持NAT
echo "配置iptables NAT规则..."

# 获取默认网络接口
DEFAULT_INTERFACE=$(ip route | grep default | awk '{print $5}' | head -n1)
if [ -z "$DEFAULT_INTERFACE" ]; then
    echo "警告: 无法检测到默认网络接口"
    echo "请手动配置NAT规则"
else
    echo "默认网络接口: $DEFAULT_INTERFACE"
    
    # 清理可能存在的旧规则
    iptables -t nat -D POSTROUTING -s "$NETWORK_SUBNET" -o "$DEFAULT_INTERFACE" -j MASQUERADE 2>/dev/null || true
    iptables -D FORWARD -i "$BRIDGE_NAME" -o "$DEFAULT_INTERFACE" -j ACCEPT 2>/dev/null || true
    iptables -D FORWARD -i "$DEFAULT_INTERFACE" -o "$BRIDGE_NAME" -j ACCEPT 2>/dev/null || true
    
    # 添加新的NAT规则
    iptables -t nat -A POSTROUTING -s "$NETWORK_SUBNET" -o "$DEFAULT_INTERFACE" -j MASQUERADE
    iptables -A FORWARD -i "$BRIDGE_NAME" -o "$DEFAULT_INTERFACE" -j ACCEPT
    iptables -A FORWARD -i "$DEFAULT_INTERFACE" -o "$BRIDGE_NAME" -j ACCEPT
fi

# 创建网络配置持久化脚本
NETWORK_PERSIST_SCRIPT="/etc/qemu-k8s-network.sh"
cat > "$NETWORK_PERSIST_SCRIPT" << EOF
#!/bin/bash
# QEMU K8s网络配置持久化脚本
# 系统启动时自动执行

# 创建网桥
if ! ip link show "$BRIDGE_NAME" >/dev/null 2>&1; then
    brctl addbr "$BRIDGE_NAME"
    ip addr add "$GATEWAY_IP/24" dev "$BRIDGE_NAME"
    ip link set "$BRIDGE_NAME" up
fi

# 启用IP转发
echo 1 > /proc/sys/net/ipv4/ip_forward

# 配置NAT规则
DEFAULT_INTERFACE=\$(ip route | grep default | awk '{print \$5}' | head -n1)
if [ -n "\$DEFAULT_INTERFACE" ]; then
    iptables -t nat -C POSTROUTING -s "$NETWORK_SUBNET" -o "\$DEFAULT_INTERFACE" -j MASQUERADE 2>/dev/null || \\
        iptables -t nat -A POSTROUTING -s "$NETWORK_SUBNET" -o "\$DEFAULT_INTERFACE" -j MASQUERADE
    
    iptables -C FORWARD -i "$BRIDGE_NAME" -o "\$DEFAULT_INTERFACE" -j ACCEPT 2>/dev/null || \\
        iptables -A FORWARD -i "$BRIDGE_NAME" -o "\$DEFAULT_INTERFACE" -j ACCEPT
    
    iptables -C FORWARD -i "\$DEFAULT_INTERFACE" -o "$BRIDGE_NAME" -j ACCEPT 2>/dev/null || \\
        iptables -A FORWARD -i "\$DEFAULT_INTERFACE" -o "$BRIDGE_NAME" -j ACCEPT
fi
EOF

chmod +x "$NETWORK_PERSIST_SCRIPT"

# 创建systemd服务文件
SERVICE_FILE="/etc/systemd/system/qemu-k8s-network.service"
cat > "$SERVICE_FILE" << EOF
[Unit]
Description=QEMU K8s Network Setup
After=network.target

[Service]
Type=oneshot
ExecStart=$NETWORK_PERSIST_SCRIPT
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
EOF

# 启用服务
systemctl daemon-reload
systemctl enable qemu-k8s-network.service

# 创建网络清理脚本
CLEANUP_SCRIPT="$SOURCE_DIR/cleanup-network.sh"
cat > "$CLEANUP_SCRIPT" << EOF
#!/bin/bash

# QEMU K8s网络清理脚本

set -e

if [ "\$EUID" -ne 0 ]; then
    echo "错误: 此脚本需要root权限运行"
    echo "请使用: sudo \$0"
    exit 1
fi

echo "清理QEMU K8s网络配置..."

# 停止并删除网桥
if ip link show "$BRIDGE_NAME" >/dev/null 2>&1; then
    echo "删除网桥: $BRIDGE_NAME"
    ip link set "$BRIDGE_NAME" down
    brctl delbr "$BRIDGE_NAME"
fi

# 清理iptables规则
echo "清理iptables规则..."
DEFAULT_INTERFACE=\$(ip route | grep default | awk '{print \$5}' | head -n1)
if [ -n "\$DEFAULT_INTERFACE" ]; then
    iptables -t nat -D POSTROUTING -s "$NETWORK_SUBNET" -o "\$DEFAULT_INTERFACE" -j MASQUERADE 2>/dev/null || true
    iptables -D FORWARD -i "$BRIDGE_NAME" -o "\$DEFAULT_INTERFACE" -j ACCEPT 2>/dev/null || true
    iptables -D FORWARD -i "\$DEFAULT_INTERFACE" -o "$BRIDGE_NAME" -j ACCEPT 2>/dev/null || true
fi

# 禁用并删除systemd服务
echo "删除systemd服务..."
systemctl disable qemu-k8s-network.service 2>/dev/null || true
rm -f "$SERVICE_FILE"
rm -f "$NETWORK_PERSIST_SCRIPT"
systemctl daemon-reload

echo "网络配置清理完成"
EOF

chmod +x "$CLEANUP_SCRIPT"

# 创建网络状态检查脚本
STATUS_SCRIPT="$SOURCE_DIR/check-network.sh"
cat > "$STATUS_SCRIPT" << EOF
#!/bin/bash

# QEMU K8s网络状态检查脚本

echo "=== QEMU K8s网络状态 ==="
echo

# 检查网桥状态
echo "网桥状态:"
if ip link show "$BRIDGE_NAME" >/dev/null 2>&1; then
    echo "✓ 网桥 $BRIDGE_NAME 已创建"
    ip addr show "$BRIDGE_NAME" | grep inet
else
    echo "✗ 网桥 $BRIDGE_NAME 不存在"
fi
echo

# 检查IP转发
echo "IP转发状态:"
if [ "\$(cat /proc/sys/net/ipv4/ip_forward)" = "1" ]; then
    echo "✓ IP转发已启用"
else
    echo "✗ IP转发未启用"
fi
echo

# 检查iptables规则
echo "NAT规则状态:"
DEFAULT_INTERFACE=\$(ip route | grep default | awk '{print \$5}' | head -n1)
if [ -n "\$DEFAULT_INTERFACE" ]; then
    echo "默认接口: \$DEFAULT_INTERFACE"
    if iptables -t nat -C POSTROUTING -s "$NETWORK_SUBNET" -o "\$DEFAULT_INTERFACE" -j MASQUERADE 2>/dev/null; then
        echo "✓ NAT规则已配置"
    else
        echo "✗ NAT规则未配置"
    fi
else
    echo "✗ 无法检测默认网络接口"
fi
echo

# 检查systemd服务
echo "服务状态:"
if systemctl is-enabled qemu-k8s-network.service >/dev/null 2>&1; then
    echo "✓ qemu-k8s-network.service 已启用"
else
    echo "✗ qemu-k8s-network.service 未启用"
fi
EOF

chmod +x "$STATUS_SCRIPT"

echo
echo "网络配置完成!"
echo "网桥名称: $BRIDGE_NAME"
echo "网桥IP: $GATEWAY_IP"
echo "网络子网: $NETWORK_SUBNET"
echo "默认接口: $DEFAULT_INTERFACE"
echo
echo "相关脚本:"
echo "- 网络状态检查: $STATUS_SCRIPT"
echo "- 网络清理: $CLEANUP_SCRIPT"
echo "- 持久化脚本: $NETWORK_PERSIST_SCRIPT"
echo
echo "网络配置已持久化，重启后自动生效"
echo "现在可以创建和启动虚拟机了"